import React, { useState } from 'react';
import s from './style.module.css';
import { Textarea, Message, Button, Form, Input, Radio } from '@knownsec/react-component';
import cn from 'classnames';
import SelectAnt from '@/components/SelectAnt';
import { putWarnSite, getWarnSite, getWarnUserList, postWarnTest } from '~/API';
import recursionForm from '@/common/recursionForm';

export default function email() {
  const [form] = Form.useForm();

  const createForm = React.useRef();
  const createForm2 = React.useRef();
  const [userLIst, setUserLIst] = useState([]);
  const [disable, setDisable] = useState(false);
  const [showAlert, setShowAlert] = useState(false);
  const validatormap = (rule, value, callback) => {
    const reg = new RegExp(
      '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
    );
    if (rule.field == 'title' && !value) {
      callback('请填写邮件标题');
    } else if (rule.field == 'content' && !value) {
      callback('请填写邮件内容');
    } else if (rule.field == 'server_host' && !value) {
      callback('请填写邮箱服务器');
    } else if (rule.field == 'server_port' && !value) {
      callback('请填写邮箱服务端口');
    } else if (rule.field == 'email' && !reg.test(value)) {
      callback('请填写邮箱地址');
    } else if (rule.field == 'password' && !value) {
      callback('请填写邮箱密码');
    } else {
      setShowAlert(false);
      return Promise.resolve();
    }
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    createForm.current.setFieldsValue(values);
  };
  const onValues2 = (data) => {
    let values = recursionForm(data);
    createForm2.current.setFieldsValue(values);
  };
  const sendForm = () => {
    createForm.current.validateFields().then(async (res) => {
      const putres = await putWarnSite(res);
      if (putres.status === 'success') {
        Message.show({
          pro: true,
          type: 'success',
          message: '修改成功',
          showClose: false,
        });
      }
    });
  };
  const sendEmail = () => {
    if (!form.getFieldValue('receiver_ids')[0]) {
      setShowAlert(true);
      return;
    }
    createForm2.current
      .validateFields()
      .then(async (res) => {
        setDisable(true);
        const putres = await postWarnTest(res).catch((err) => {
          return err
        })
        if (putres.status === 'success') {
          Message.show({
            pro: true,
            type: 'success',
            message: '发送成功',
            showClose: false,
          });
        }else{
          Message.show({
            pro: true,
            type: 'error',
            message: putres.message||'操作失败',
            showClose: false,
          });
        }
        setDisable(false);
      });
  };
  React.useEffect(async () => {
    const res = await getWarnSite();
    const user = await getWarnUserList({ all: 1 });
    const user_ = user.data.data.map((e) => {
      return { label: e.contact_name, value: e.receiver_id };
    });
    setUserLIst(user_);
    createForm.current.setFieldsValue(res.data.data);
    createForm2.current.setFieldsValue({ email: res.data.data.email });
  }, []);
  return (
    <div className={s.emailBox}>
      <div className={s.emailBox1}>
        <div className={s.tital}>邮箱配置</div>
        <Form
          ref={createForm}
          onValuesChange={(newItem, allValues) => {
            onValues(newItem, allValues);
          }}
        >
          <p className={s.itemP}>
            <span>邮箱协议</span>
            <span>SMTP</span>
          </p>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="server_host"
            label="邮箱服务器"
            validateTrigger="onBlur"
          >
            <Input
              pro
              className={s.inpName}
              maxlength={50}
              placeholder="请输入邮箱服务器地址"
              autoComplete={'off'}
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="server_port"
            label="服务端口"
          >
            <Input
              pro
              className={s.inpName}
              maxlength={50}
              placeholder="请输入邮箱服务使用端口"
              autoComplete={'off'}
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="email"
            label="邮箱"
          >
            <Input
              pro
              autoComplete={'off'}
              className={s.inpName}
              maxlength={50}
              placeholder="请输入邮箱账号"
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="password"
            label="邮箱密码"
          >
            <Input
              pro
              autoComplete={'off'}
              className={s.inpName}
              maxlength={50}
              type="password"
              placeholder="请输入邮箱密码"
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="encrypt"
            label="加密类型"
          >
            <Radio.Group className={s.radioBorder}>
              <Radio value={0} className={s.radio0}>
                不加密
              </Radio>
              <Radio value={1} className={s.radio0}>
                SSL加密
              </Radio>
              <Radio value={2} className={s.radio0}>
                STARTTLS加密
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            rules={[{ required: false, validator: validatormap }]}
            name="email_prefix"
            label="邮件前缀"
          >
            <Input
              pro
              className={s.inpName}
              autoComplete={'off'}
              maxlength={50}
              placeholder="请输入收到邮件标题的前缀"
            ></Input>
          </Form.Item>
        </Form>
        <Button
          pro
          type="primary"
          onClick={() => {
            sendForm();
          }}
        >
          确定修改
        </Button>
      </div>
      <div className={s.emailBox2}>
        <div className={s.tital}>邮箱测试</div>
        <Form
          form={form}
          ref={createForm2}
          onValuesChange={(newItem, allValues) => {
            onValues2(newItem, allValues);
          }}
          validateTrigger="onBlur"
        >
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="email"
            label="发件人"
          >
            <Input
              pro
              disabled={true}
              className={s.inpName}
              autoComplete={'off'}
              maxlength={50}
              placeholder=""
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="receiver_ids"
            label="收件人"
            initialValue={[]}
          >
            <SelectAnt pro option={userLIst} mode="multiple" className={s.inpName} />
          </Form.Item>
          <div className={s.alert} style={{ display: showAlert ? 'block' : 'none' }}>
            请填写邮箱地址
          </div>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="title"
            label="邮箱标题"
          >
            <Input
              pro
              autoComplete={'off'}
              className={s.inpName}
              maxlength={50}
              placeholder="请输入邮箱标题"
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="content"
            label="邮箱内容"
          >
            <Textarea className={s.textArea} placeholder="请输入邮箱内容"></Textarea>
          </Form.Item>
        </Form>
        <Button
          pro
          type="primary"
          onClick={() => {
            sendEmail();
          }}
          disabled={disable}
        >
          测试
        </Button>
      </div>
    </div>
  );
}
